<template>
  <el-container v-loading="loading" :class="{ 'is-perview': isPreview }" class="wk-print-container">
    <el-header >
      <template v-if="isPreview">
        <el-button type="primary" @click="handleClick('download')">{{ `${perviewTypeName} 下载` }}</el-button>
        <el-button type="primary" @click="handleClick('print')">打印</el-button>
        <el-button @click="handleClick('goback')">取消</el-button>
      </template>
      <template v-else>
        <span class="select-label">选择模版</span>
        <el-select
          v-model="templateId"
          style="width: 170px;"
          class="handle-item-content"
          @change="getDetail">
          <el-option
            v-for="item in templateOptions"
            :key="item.templateId"
            :label="item.templateName"
            :value="item.templateId"/>
        </el-select>
        <span class="select-label">选择模版</span>
        <el-select v-model="perviewType" style="width: 80px;" class="handle-item-content">
          <el-option v-for="item in previewOptions" :key="item"
            :label="item"
            :value="item"/>
        </el-select>

        <el-button class="preview-button" type="primary" @click="printPreviewClick">打印预览</el-button>
      </template>
    </el-header>
    <el-main>
      <div class="main-container">
        <div class="main-content">
          <iframe
            v-show="isPreview"
            id="wkPrint"
            :height="iframeHeight"
            :src="iframeUrl"
            style="width: 100%;margin-top: 54px;"
            scrolling="no"
            frameborder="0"/>
        </div>
        <div v-show="!isPreview" class="main-tips">您可以在当前页面对模版文字进行调整，确认无误后可进行打印</div>
        <div v-show="!isPreview" class="main-content">
          <tinymce
            ref="editor" :toolbar="[]" v-model="content" :init="{
              statusbar: false,
              plugins: 'print autoresize',
              extended_valid_elements: 'span[class|title|wktag|style|contenteditable]',
              content_style: ' body {padding: 60px !important;width: 595px; margin: 0 auto;} p { margin: 5px 0;}',
          }" class="rich-txt" />
        </div>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
// todo whf 这里页面里，有几个this.$route和一个onBeforeRouteUpdate没有仔细处理
import Tinymce from '/src/components/Tinymce'
import crmTypeModel from '/src/views/crm/model/crmTypeModel'
import { downloadFileWithBuffer } from '/src/utils/index.js'
import {crmFileDownByPathAPI, downloadFileAPI} from "/src/api/common.js";
import {
  printPrintAPI,
  printRecordDetailAPI,
  printSaveRecordAPI,
  printTemplateListAPI,
  printPreviewAPI
} from '/src/api/admin/crm'

defineOptions({
  name: 'Print',
})


const loading=ref(false)
const isPreview=ref(false) // 是编辑 还是打印预览
const templateOptions=ref([])
const templateId=ref('')
const typeId=ref('') // 模块对应的id
const previewOptions=ref(['word', 'pdf'])
const perviewType=ref('word')
const content=ref('')
const historyData=ref(null)

    // 预览
const iframeUrl=ref('')
const iframeHeight=ref(document.documentElement.clientHeight - 170)
const srcData=ref(null)

const perviewTypeName = computed(() => {
  return {
    word: 'Word',
    pdf: 'PDF'
  }[perviewType.value]
})
function created() {
  if (this.$route.query.type == 'history') {
    getRecordDetail()
  } else {
    typeId.value = this.$route.query.id
    getTemplateOptions(crmTypeModel.convertKeyToType(this.$route.query.module))
  }

  window.addEventListener('resize', changeIframeHeight.value)
}
created()


onBeforeUnmount(() => {
  window.removeEventListener('resize', changeIframeHeight.value)
})

onBeforeRouteUpdate((to, from, next) => {
  content.value = ''
  next()
})

function changeIframeHeight() {
  iframeHeight.value = document.documentElement.clientHeight - 170
}

/**
 * 获取模板配置
 */
function getTemplateOptions(type) {
  loading.value = true
  printTemplateListAPI({
    type: type,
    pageType: 0
  })
      .then(res => {
        templateOptions.value = res.data.data.list || []
        if (this.$route.query.type != 'history') {
          if (templateOptions.value.length) {
            templateId.value = templateOptions.value[0].templateId
            getDetail()
          } else {
            templateId.value = ''
          }
        }

        loading.vale = false
      })
      .catch(() => {
        loading.value = false
      })
}

/**
 * 详情
 */
function getDetail() {
  loading.value = true
  printPrintAPI({
    templateId: templateId.value,
    id: typeId.value
  })
      .then(res => {
        loading.value = false
        content.value = res.data.data
      })
      .catch(() => {
        loading.value = false
      })
}

/**
 * 详情
 */
function getRecordDetail() {
  loading.value = true
  printRecordDetailAPI({
    recordId: this.$route.query.recordId
  })
      .then(res => {
        loading.value = false
        const data = res.data.data || {}
        historyData.value = data
        templateId.value = data.templateId
        typeId.value = data.typeId

        getTemplateOptions(data.crmType)
        content.value = data.recordContent || ''
      })
      .catch(() => {
        loading.value = false
      })
}

/**
 * 打印
 */
function compactPrint() {
  cxt.refs.editor.editor.execCommand('mcePrint')
  savePrintRecord()
}

/**
 * 打印预览
 */
function printPreviewClick() {
  loading.value = true
  printPreviewAPI({
    type: perviewType.value,
    content: content.value
  })
      .then(res => {
        loading.value = false
        const data = res.data.data
        const iframeUrl = `/crmPrint/preview.pdf?type=1&key=${data}`
        downloadFileAPI(iframeUrl).then(res => {
          iframeUrl.value = window.URL.createObjectURL(res.data)
        }).catch(() => {})

        srcData.value = data
        isPreview.value = true
      })
      .catch(() => {
        loading.value = false
      })
}

/**
 *保存打印记录
 */
function savePrintRecord() {
  if (templateId.value && typeId.value) {
    printSaveRecordAPI({
      templateId: templateId.value,
      typeId: typeId.value,
      recordContent: content.value
    })
        .then(res => {
        })
        .catch(() => {
        })
  }
}

function hidenView() {
  emits('close')
}

/** 预览页面逻辑 */

function handleClick(type) {
  if (type == 'goback') {
    isPreview.value = false
  } else if (type == 'print') {
    document.getElementById('wkPrint').contentWindow.print() // 调用浏览器的打印功能打印指定区域
    savePrintRecord()
  } else if (type == 'download') {
    if (srcData.value) {
      var ext = perviewType.value
      const path = srcData.value
      var data = {
        key: path,
        type: ext === 'word' ? 2 : 1
      }
      ext = ext === 'word' ? 'doc' : 'pdf'
      crmFileDownByPathAPI(data).then(res => {
        const blob = new Blob([res.data], {
          type: ''
        })
        downloadFileWithBuffer(blob, `文档.${ext}`)
      }).catch(() => {})
    }
  }
}




</script>
<script>






export default {

  components: {
    // Tinymce
  },
  props: {},
  data() {
    return {

    }
  },
  computed: {

  },
  created() {

  },
  beforeRouteUpdate(to, from, next) {

  },
  beforeDestroy() {

  },
  methods: {

  }
}
</script>

<style lang="scss" scoped>
.wk-print-container {
  .el-header {
    background-color: white;
    box-shadow: 0px 1px 2px #dbdbdb;
    line-height: 60px;
    padding: 0 70px;
    z-index: 1;
    position: relative;

    .select-label {
      margin-right: 15px;
    }

    .el-select + .select-label {
      margin-left: 30px;
    }
  }

  .preview-button {
    position: absolute;
    right: 70px;
    top: 16px;
  }

  .el-main {
    padding: 0;
  }

  &.is-perview {
    .el-header {
      text-align: right;
    }
  }
}

.main-container {
  height: 100%;
  overflow: auto;

  .main-tips {
    text-align: center;
    font-size: 13px;
    margin: 20px 0;
    color: #BFBFBF;
  }

  .main-content {
    width: 66%;
    margin: 0 auto;
  }
}

</style>
